package kz.kstu.ds.xml;

import kz.kstu.ds.entity.SignedDocument;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.*;

/**
 * Date: 04.11.12
 * Time: 19:56
 *
 * @author Oleg Anastassov
 */
public final class JAXBHelper {

    private JAXBHelper() {
    }

    public static void marshall(SignedDocument doc, File file) throws JAXBException, IOException {
        JAXBContext context = JAXBContext.newInstance(SignedDocument.class);
        Marshaller m = context.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        m.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
        m.marshal(doc, System.out);

        Writer w = null;
        try {
            w = new FileWriter(file);
            m.marshal(doc, w);
        } finally {
            try {
                w.close();
            } catch (Exception ignored) {
            }
        }
    }

    public static SignedDocument unmarshal(File f) throws JAXBException, FileNotFoundException {
        JAXBContext context = JAXBContext.newInstance(SignedDocument.class);
        Unmarshaller um = context.createUnmarshaller();
        SignedDocument doc = (SignedDocument) um.unmarshal(new FileReader(f.getName()));
        return doc;
    }

}
